<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
        :before-open="outBeforeOpen"
        @selection-change="selectionChange"
        @cell-click="cellClick"
      >
        <template slot-scope="scope" slot="menuLeft">
          <el-button
            type="primary"
            size="small"
            v-permission="false"
            @click.stop="handleDownload"
            >下 载
          </el-button>
          <el-button type="primary" size="small" @click="handleAdd"
          >添 加
          </el-button>
          <el-button type="primary" size="small" @click.stop="handleExportWrite"
            >导 出
          </el-button>
          <el-button
            type="primary"
            size="small"
            v-permission="permissionList.outputApplyBtn"
            @click.stop="outputApply()"
            >出库修改提交
          </el-button>
          <el-button
            type="primary"
            size="small"
            v-permission="permissionList.outputApproveBtn"
            @click.stop="outputApprove()"
            >出库修改审批
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="outputBatchComplete()"
          >出库操作
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="delBatchs()"
          >删除
          </el-button>
	  <el-button
            type="primary"
            size="small"
	    v-permission="permissionList.delBtn"
            @click="superDelBatchs()"
          >高级删除
          </el-button>
          <el-button
            type="primary"
            size="small"
            :hidden="true"
            v-if="false"
            @click.stop="handlePrint"
            >打 印
          </el-button>
        </template>
        <template slot="menuForm" slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click.stop="handleKeeper2Confirm"
            >库管2确认
          </el-button>
        </template>
        <template slot="boxNoForm">
          <el-input
            placeholder="扫码输入"
            v-model="form.boxNo"
            v-focus
            @keyup.enter.native="searchInputDetail"
          >
          </el-input>
        </template>
        <template slot="menu" slot-scope="{ row, index }">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            v-if="row.checkApproveStatus=='3'"
            v-permission="permissionList.editBtn"
            @click="rowEdit(row, index)"
          >编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-document-copy"
            v-if="row.dataSource=='0'||row.dataSource=='1'||row.dataSource=='2'||row.dataSource=='3'"
            v-permission="permissionList.completeBtn"
            @click="rowCompleteInfo(row, index)"
          >完善信息
          </el-button>
        </template>
      </avue-crud>
      <open-dialog title="完善信息" :DialogVisible.sync="completeVisableDialog">
        <el-form label-width="60px">
          <avue-form
            v-model="formComplete.swStOutputDetail"
            :option="tableOptionComplete"
            ref="completeforms"
          >
          </avue-form>
          <div class="bottom-menu-complete">
            <el-button type="primary" size="small" @click="inputDetailComplete()">保存</el-button>
            <el-button type="primary" size="small" @click="completeVisableDialog = false"
              >取消</el-button
            >
            <el-button
                type="primary"
                size="small"
                @click.stop="keeper2ConfirmsComplete"
              >库管2确认
            </el-button>
          </div>
        </el-form>
      </open-dialog>
      <open-dialog title="添加" :DialogVisible.sync="addVisableDialog">
        <el-form label-width="60px">
          <avue-form
            v-model="formAdd.swStOutputDetail"
            :option="tableOptionAdd"
            ref="outputforms"
          >
            <template slot="boxNo">
              <el-input
                placeholder="扫码输入"
                v-model="formAdd.swStOutputDetail.boxNo"
                v-focus
                @keyup.enter.native="searchInputDetailOfAdd"
              >
              </el-input>
            </template>
          </avue-form>
          <dynamic-crud
            title="出库明细"
            :data="formAdd.swStOutputDetailList"
            :option="tableOptionAddDetail"
            :rowAdd="rowadd"
          ></dynamic-crud>
          <div class="bottom-menu-input">
            <el-button type="primary" size="small" @click="inputDetailSave()">保存</el-button>
            <el-button type="primary" size="small" @click="addVisableDialog = false"
              >取消</el-button
            >
            <el-button
                type="primary"
                size="small"
                @click.stop="keeper2Confirms"
              >库管2确认
            </el-button>
          </div>
        </el-form>
      </open-dialog>
      <open-dialog title="出库操作" :DialogVisible.sync="batchCompleteVisableDialog">
        <el-form label-width="60px">
          <avue-form
            v-model="formBatchComplete.swStOutputDetail"
            :option="tableOptionBatchComplete"
            ref="batchCompleteforms"
          >
          </avue-form>
          <div class="bottom-menu-complete">
            <el-button type="primary" size="small" @click="outputDetailBatchComplete()">保存</el-button>
            <el-button type="primary" size="small" @click="batchCompleteVisableDialog = false"
              >取消</el-button
            >
            <el-button
                type="primary"
                size="small"
                @click.stop="keeper2BatchConfirmsComplete"
              >库管2确认
            </el-button>
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import baseCrud from "@/mixins/base-crud";
import { handleDownloadZip } from "@/util/util.js";
  import {handleExcelResponse} from "@/util/util";
import { dateFormat } from "@/util/date";
import { checkPwd } from "@/api/admin/user";
import store from "@/store";
import {
  fetchList,
  //getInputDetailByBoxNo,
  exportByIds,
  addObj,inventoryOutType,exportAll,applyed,approved,putObj,putBatchObj,delBatch
} from "@/api/subway/swstoutputdetail";
import {
  getInputDetailByBoxNo
} from "@/api/subway/swstinputdetail";
import {tableOptionAdd,tableOptionAddDetail,tableOptionComplete,tableOptionBatchComplete,startDate, endDate} from "@/const/crud/subway/swstoutputdetail";

export default {
  name: "SwStOutputDetail",
  mixins: [baseCrud("subway/swstoutputdetail")],
  data() {
    return {
      exportName: "车票出库.xlsx",
        selectKeys: [], //存放对像
        selectKeyVals: [], //存放值
        tableOptionAdd: tableOptionAdd,
        tableOptionAddDetail: tableOptionAddDetail,
        formAdd:{
          swStOutputDetail: {},
          swStOutputDetailList: []
        },
        formComplete:{
          swStOutputDetail: {}
        },
        addVisableDialog: false,
        completeVisableDialog: false,
        isKeeper2Confirm: false,
        searchForm: {
          dates1: [startDate, endDate],
        },
        tableOptionComplete: tableOptionComplete,
        tableOptionBatchComplete: tableOptionBatchComplete,
        batchCompleteVisableDialog: false,
        formBatchComplete:{
          ids:[],
          swStOutputDetail: {}
        },
    };
  },
  computed: {
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.st_output_detail_add, false),
        delBtn: this.vaildData(this.permissions.st_output_detail_delete, false),
        editBtn: this.vaildData(
          this.permissions.st_output_detail_update,
          false
        ),
        completeBtn: this.vaildData(this.permissions.st_output_detail_complete,false),
        downloadBtn: this.vaildData(
          this.permissions.st_output_detail_download,
          false
        ),
        outputApplyBtn: this.vaildData(this.permissions.st_output_detail_apply, false),
        outputApproveBtn: this.vaildData(this.permissions.st_output_detail_approve, false)
      };
    },
  },
  watch: {
    "form.keeper2code"(newValue, oldValue) {
      // 库管2变化后将确认状态置为false
      this.form.keeper2Confirmed = false;
    },
    "formAdd.swStOutputDetail.keeper2code"(newValue, oldValue) {
      // 库管2变化后将确认状态置为false
      this.isKeeper2Confirm = false;
    },
    "formComplete.swStOutputDetail.stockArea"(val){
      //获取渲染列
      var stockArea = this.findObject(this.tableOptionComplete.group[0].column, "stockArea");
      //如果库区不为空，不允许修改
      if (val != "" && val != null && val != undefined) {
        stockArea.disabled = true
      }else{
        stockArea.disabled = false
      }
    }
  },
  methods: {
    //删除操作
    delBatchs: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据！");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.stockArea != "" && table.stockArea != null && table.stockArea != undefined) {
          this.$message.error("请检查数据，只能选择无库区的数据！");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delBatch(ids)
          .then((data) => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },
     //高级删除操作
    superDelBatchs: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据！");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delBatch(ids)
          .then((data) => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },
    //出库操作
    outputBatchComplete(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      for (const table of this.$refs.crud.tableSelect) {
        if (table.stockArea != "" && table.stockArea != null && table.stockArea != undefined) {
          this.$message.error("请检查数据，只能选择无库区的数据！");
          return false;
        }
      }
      this.formBatchComplete.ids = [];
      for (var i in this.formBatchComplete.swStOutputDetail) {
        this.formBatchComplete.swStOutputDetail[i] = null;
      }
      this.isKeeper2Confirm = false;
      this.batchCompleteVisableDialog = true;
    },
    outputDetailBatchComplete(){
      for (const table of this.$refs.crud.tableSelect) {
        this.formBatchComplete.ids.push(table.id);
      }
      this.$refs.batchCompleteforms.validate(vaild=>{
        if(vaild){
          if(!this.isKeeper2Confirm){
            this.$message.warning("请先进行库管2确认");
            return;
          }
          putBatchObj(this.formBatchComplete).then(data => {
              this.$message.success("操作成功");
              this.getList(this.page);
              this.batchCompleteVisableDialog = false;
              done();
            })
            .catch(() => {});
        }
      })
    },
    rowCompleteInfo(row){
      this.isKeeper2Confirm = false;
      this.formComplete.swStOutputDetail = row;
      this.completeVisableDialog = true;
    },
    inputDetailComplete(){
      this.$refs.completeforms.validate(vaild=>{
        if(vaild){
          if(!this.isKeeper2Confirm){
            this.$message.warning("请先进行库管2确认");
            return;
          }
          putBatchObj(this.formComplete).then(data => {
              this.$message.success("完善成功");
              this.getList(this.page);
              this.completeVisableDialog = false;
              done();
            })
            .catch(() => {});
        }
      })
    },
    outputApply: function() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.checkApproveStatus != "1" && table.checkApproveStatus != "4") {
          this.$message.error("请检查数据，只能选择审批状态为未申请或审批未通过的数据进行申请！");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        applyed(ids)
          .then(data => {
            this.$message.success("申请成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    outputApprove: function() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.checkApproveStatus != "2") {
          this.$message.error("请检查数据，只能选择审批状态为已申请的数据进行审批！");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        approved(ids)
          .then(data => {
            this.$message.success("日计划审批成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    handleAdd(){
      for (var i in this.formAdd.swStOutputDetail) {
        this.formAdd.swStOutputDetail[i] = null;
      }
      this.formAdd.swStOutputDetailList = [];
      this.isKeeper2Confirm = false;
      let now = new Date();
      this.formAdd.swStOutputDetail.outGoingTime = dateFormat(now);
      this.addVisableDialog = true;
    },
    inputDetailSave(){
      this.$refs.outputforms.validate(vaild=>{
        if(vaild){
          if (this.formAdd.swStOutputDetailList.length==0) {
            this.$message.warning("请填写出库明细信息！");
            return;
          }
          for (const item of this.formAdd.swStOutputDetailList) {
            if (
              this.validatenull(item.ticketType) ||
              this.validatenull(item.ticketName) ||
              this.validatenull(item.ticketNumber) ||
              this.validatenull(item.stockArea)
            ) {
            // ||
            //   this.validatenull(item.latestStartTime)
              this.$message.info(
                "出库明细中的票种、车票名称、车票数量、库区分区不能为空！"
              );
              return;
            }
          }
          if(!this.isKeeper2Confirm){
            this.$message.warning("请先进行库管2确认");
            return;
          }
          addObj(this.formAdd)
            .then((data) => {
              this.$message.success("添加成功");
              this.getList(this.page);
              this.addVisableDialog = false;
              done();
            })
            .catch(() => {});
        }
      })
    },
    selectionChange(list){
      this.selectKeys = list;
      this.selectKeyVals = [];
      for (let i = 0; i < list.length; i++) {
        this.selectKeyVals.push(list[i].id);
      }
    },
    keeper2ConfirmsComplete() {
      if (!this.formComplete.swStOutputDetail.keeper2code) {
        this.$message.info("请先选择库管2");
        return;
      }
      // if (this.formComplete.swStOutputDetail.keeper2code == store.getters.userInfo.userCode) {
      //   this.$message.error("请检查库管2，不能本人进行确认！");
      //   return false;
      // }
      this.$prompt("请输入密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({ value }) => {
          checkPwd(this.formComplete.swStOutputDetail.keeper2code, value).then((response) => {
            var result = response.data.data;
            if (result) {
              this.isKeeper2Confirm = true;
              this.$message.success("确认成功");
            } else {
              this.$message.error("密码错误");
            }
          });
        })
        .catch(() => {});
    },
    keeper2Confirms() {
      if (!this.formAdd.swStOutputDetail.keeper2code) {
        this.$message.info("请先选择库管2");
        return;
      }
      // if (this.formAdd.swStOutputDetail.keeper2code == store.getters.userInfo.userCode) {
      //   this.$message.error("请检查库管2，不能本人进行确认！");
      //   return false;
      // }
      this.$prompt("请输入密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({ value }) => {
          checkPwd(this.formAdd.swStOutputDetail.keeper2code, value).then((response) => {
            var result = response.data.data;
            if (result) {
              this.isKeeper2Confirm = true;
              this.$message.success("确认成功");
            } else {
              this.$message.error("密码错误");
            }
          });
        })
        .catch(() => {});
    },
    keeper2BatchConfirmsComplete() {
      if (!this.formBatchComplete.swStOutputDetail.keeper2code) {
        this.$message.info("请先选择库管2");
        return;
      }
      // if (this.formBatchComplete.swStOutputDetail.keeper2code == store.getters.userInfo.userCode) {
      //   this.$message.error("请检查库管2，不能本人进行确认！");
      //   return false;
      // }
      this.$prompt("请输入密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({ value }) => {
          checkPwd(this.formBatchComplete.swStOutputDetail.keeper2code, value).then((response) => {
            var result = response.data.data;
            if (result) {
              this.isKeeper2Confirm = true;
              this.$message.success("确认成功");
            } else {
              this.$message.error("密码错误");
            }
          });
        })
        .catch(() => {});
    },
    rowadd(callback){
      callback()
    },
    outBeforeOpen(done, type) {
      if (type == "add") {
        setTimeout(() => {
          this.form.outGoingTime = dateFormat(new Date());
          //给附件置空
          this.form.filePath = "";
        });
      }
      done();
    },

    getList(page) {
      this.tableLoading = true;
      return fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          this.params,
          this.searchForm
        )
      ).then((response) => {
        this.tableData = response.data.data.records;
        this.tableData.forEach((row) => {
          if(!this.validatenull(row.stockArea)){
            row.stockArea = Number(row.stockArea);
          }
        });
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    beforeRowSave(row, callback, loading) {
      if (!row.keeper2Confirmed) {
        this.$message.info("请先进行库管2确认");
        loading();
      } else {
        callback();
      }
    },
    beforeRowUpdate(row, index, callback, loading) {
      if (!row.keeper2Confirmed) {
        this.$message.info("请先进行库管2确认");
        loading();
      } else {
        callback();
      }
    },
    cellClick(row, column, cell, event) {
      if (column.property == "ticketNo") {
        this.$alert(row.ticketNo);
      }
    },
    handleKeeper2Confirm() {
      if (!this.form.keeper2code) {
        this.$message.info("请先选择库管2");
        return;
      }
      // if (this.form.keeper2code == store.getters.userInfo.userCode) {
      //   this.$message.error("请检查库管2，不能本人进行确认！");
      //   return false;
      // }
      this.$prompt("请输入密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({ value }) => {
          checkPwd(this.form.keeper2code, value).then((response) => {
            var result = response.data.data;
            if (result) {
              this.$message.success("确认成功");
            } else {
              this.$message.error("密码错误");
            }
            this.form.keeper2Confirmed = result;
          });
        })
        .catch(() => {});
    },
    searchInputDetail() {
      getInputDetailByBoxNo(this.form.boxNo).then((response) => {
        let result = response.data.data;
        this.form.ticketType = result.ticketType;
        this.form.ticketName = result.ticketName;
        this.form.ticketTimes = result.ticketTimes;
        this.form.ticketPrice = result.ticketPrice;
        this.form.ticketNumber = result.ticketNumber;
        this.form.activeTime = result.activeTime;
        this.form.latestStartTime = result.latestStartTime;
        this.form.ticketNo = result.ticketNo;
        this.form.stockArea = result.stockArea;
      });
    },
    searchInputDetailOfAdd() {
      getInputDetailByBoxNo(this.formAdd.swStOutputDetail.boxNo).then((response) => {
        let result = response.data.data;
        this.formAdd.swStOutputDetail.ticketType = result.ticketType;
        this.formAdd.swStOutputDetail.ticketName = result.ticketName;
        this.formAdd.swStOutputDetail.ticketTimes = result.ticketTimes;
        this.formAdd.swStOutputDetail.ticketPrice = result.ticketPrice;
        this.formAdd.swStOutputDetail.ticketNumber = result.ticketNumber;
        this.formAdd.swStOutputDetail.activeTime = result.activeTime;
        this.formAdd.swStOutputDetail.latestStartTime = result.latestStartTime;
        this.formAdd.swStOutputDetail.ticketNo = result.ticketNo;
        this.formAdd.swStOutputDetail.stockArea = result.stockArea;
      });
    },
    handleDownload() {
      let pathList = [];
      this.tableData.forEach((row) => {
        if (!this.validatenull(row.filePath)) {
          pathList.push(row.filePath);
        }
        if (!this.validatenull(row.picturePath)) {
          pathList.push(row.picturePath);
        }
      });
      if (pathList.length == 0) {
        this.$message.info("无附件");
        return;
      }
      handleDownloadZip(pathList, "车票出库附件.zip");
    }, async handleExportWrite(){ // 导出
//        console.log(this.selectKeys);
//        console.log(this.tableData);
        if (this.selectKeys.length > 0) {
          let reqdata = this.selectKeys;
          reqdata.forEach((row) => {
            row.outGoingType = row.$outGoingType;
            row.stockArea = row.$stockArea;
            row.ticketName = row.$ticketName;
            row.ticketType = row.$ticketType;
          })
          let p = JSON.stringify(reqdata);
          let res = await exportByIds(p);
          handleExcelResponse(res, "车票出库.xlsx");
        } else {//导出搜索全部
          let reqdata = [];
          let inventorys=[];
          await inventoryOutType().then((response) => {
            inventorys = response.data.data;
          });
          await fetchList(
            Object.assign(
              {
                current: 1,
                size: 999999999,
              },
              this.params,
              this.searchForm
            )
          ).then((response) => {
            reqdata = response.data.data.records;
          });
          if (null != reqdata && reqdata.length >  0) {
            let p = {};
            p['swStOutDetailExcelBean'] = reqdata;
            p['sysDictItemBean'] = inventorys;
            let res =  await exportAll(p);
            handleExcelResponse(res, "车票出库.xlsx");
          }else {
            this.$message.warning("无导出数据");
          }
          // let reqdata = this.tableData;
          // reqdata.forEach((row) => {
          //   row.outGoingType = row.$outGoingType;
          //   row.stockArea = row.$stockArea;
          //   row.ticketName = row.$ticketName;
          //   row.ticketType = row.$ticketType;
          // })
          // let p = JSON.stringify(reqdata);
          // let res = await exportByIds(p);
          // handleExcelResponse(res, "车票出库.xlsx");
        }
      }
  },
  directives: {
    //注册一个局部的自定义指令 v-focus
    focus: {
      // 指令的定义
      inserted: function (el) {
        // 聚焦元素
        el.querySelector("input").focus();
      },
    },
  },
};
</script>

<style lang="scss" scoped>
  .bottom-menu-input {
    margin-top: 48px;
    text-align: right;
  }
  .bottom-menu-complete {
    margin-top: 5px;
    text-align: right;
  }
</style>
